<template>
  <view class="position-detail-container">
    <!-- 页头 -->
    <CustomHeader></CustomHeader>
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <text class="header-title">职位详情</text>
        <view class="header-right">
          <view class="header-btn" @click="reportJob">
            <image class="header-btn-icon" src="/static/icons/candidate/report.png"></image>
          </view>
          <view 
            class="header-btn" 
            @click="toggleCollectJob"
            :class="{ 'collecting': collectLoading }"
          >
            <image 
              class="header-btn-icon" 
              :src="isCollected ? '/static/icons/candidate/collect_active.png' : '/static/icons/candidate/collect.png'"
            ></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 职位详情内容 -->
    <view v-else-if="jobDetail" class="content">
      <!-- 职位基本信息 -->
      <view class="job-basic-info">
        <view class="job-header">
          <text class="job-name">{{ jobDetail.jobInfo.jobName }}</text>
          <text class="job-salary">{{ formatSalary(jobDetail.jobInfo) }}</text>
        </view>
        
        <!-- 城市和学历要求 -->
        <view class="job-requirements">
          <view class="requirement-item">
            <image class="requirement-icon" src="/static/icons/company/location_fill.png"></image>
            <text class="requirement-text">{{ jobDetail.jobInfo.city }}</text>
          </view>
          <view class="requirement-item">
            <image class="requirement-icon" src="/static/icons/candidate/edu.png" style="width: 43rpx; height: 43rpx;;"></image>
            <text class="requirement-text">{{ jobDetail.jobInfo.edu }}</text>
          </view>
        </view>

      </view>

      <!-- HR信息 -->
      <view class="hr-section" @click="goToHrHome">
        <view class="hr-content">
          <image 
            class="hr-avatar" 
            :src="jobDetail.hrInfo.face || '/static/images/avatar.png'"
          ></image>
          <view class="hr-info">
            <text class="hr-name">{{ jobDetail.hrInfo.name || 'HR' }}</text>
            <view class="hr-details">
              <text class="company-name">{{ jobDetail.hrInfo.companyName }}</text>
              <text class="separator">·</text>
              <text class="hr-position">{{ jobDetail.hrInfo.position }}</text>
            </view>
          </view>
        </view>
        <uni-icons type="arrowright" size="18" color="#c0c0c0"></uni-icons>
      </view>

      <!-- 职位详情 -->
      <view class="job-detail-section">
        <view class="section-title">职位详情</view>
        
        <!-- 职位标签 -->
        <view class="job-tags" v-if="jobTagsList.length > 0">
          <view 
            class="job-tag" 
            v-for="tag in jobTagsList" 
            :key="tag"
          >
            <text class="tag-text">{{ tag }}</text>
          </view>
        </view>

        <!-- 职位描述 -->
        <view class="job-description">
          <rich-text 
            class="description-html" 
            :nodes="jobDetail.jobInfo.jobDescHtml"
          ></rich-text>
        </view>
      </view>

      <!-- 员工福利 -->
      <view class="benefits-section" v-if="allBenefits.length > 0">
        <view class="section-title">员工福利</view>
        <view class="benefits-list">
          <view 
            class="benefit-item" 
            v-for="benefit in allBenefits" 
            :key="benefit.dataKey"
          >
            <image 
              v-if="benefit.icon" 
              class="benefit-icon" 
              :src="benefit.icon"
            ></image>
            <text class="benefit-text">{{ benefit.value }}</text>
          </view>
        </view>
      </view>

      <!-- 公司信息 -->
      <view class="company-section">
        <view class="section-title">公司信息</view>
        <view class="company-info">
          <image 
            class="company-logo" 
            :src="jobDetail.companyInfo.logo || '/static/images/company-default.png'"
          ></image>
          <view class="company-details">
            <text class="company-name">{{ jobDetail.companyInfo.companyName }}</text>
            <view class="company-info-list">
              <text class="info-item">{{ formatFinancStage(jobDetail.companyInfo.financStage) }}</text>
              <text class="separator">·</text>
              <text class="info-item">{{ formatPeopleSize(jobDetail.companyInfo.peopleSize) }}</text>
              <text class="separator">·</text>
              <text class="info-item">{{ jobDetail.companyInfo.industry }}</text>
            </view>
          </view>
          <uni-icons type="arrowright" size="18" color="#c0c0c0"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-container">
      <text class="error-text">获取职位详情失败</text>
      <view class="retry-btn" @click="fetchJobDetail">
        <text class="retry-text">重试</text>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-actions" v-if="jobDetail">
      <view class="action-btn communicate-btn" @click="goToChat">
        <text class="btn-text">沟通</text>
      </view>
      <view class="action-btn apply-btn" @click="goToChatAndApply">
        <text class="btn-text">投递简历</text>
      </view>
    </view>

    <!-- 举报功能已改为页面跳转，移除弹出层 -->
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import CustomHeader from '@/components/CustomHeader.vue';
import { getJobSearchDetailApi } from '@/api/position.js';
import { getDictionaryDataListByTypesApi } from '@/api/company.js';
import { dictionaryCacheManager } from '@/utils/cache.js';
import { collectJobApi, uncollectJobApi, isJobCollectedApi } from '@/api/position.js';
import { createCandidateChatSessionApi } from '@/api/chat.js';
import { useSessionStore } from '@/stores/modules/session';

// 页面参数
const jobId = ref('');

// 数据状态
const loading = ref(true);
const jobDetail = ref(null);
const jobTagsList = ref([]);
const allBenefits = ref([]);

// 收藏状态管理
const isCollected = ref(false);
const collectLoading = ref(false);

// 举报相关状态（已移除弹出层相关代码）

// 页面加载时获取参数
onLoad((options) => {
  jobId.value = options.jobId || '';
  console.log('页面加载，获取到的jobId:', jobId.value);
  
  // 获取到参数后立即获取职位详情
  if (jobId.value) {
    fetchJobDetail();
  } else {
    console.error('缺少jobId参数');
    loading.value = false;
  }
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 举报职位
const reportJob = () => {
  if (!jobId.value) {
    uni.showToast({
      title: '职位信息获取失败',
      icon: 'none'
    });
    return;
  }
  
  uni.navigateTo({
    url: `/pages/candidate/position/reportReason?jobId=${jobId.value}`
  });
};

// 检查职位收藏状态
const checkCollectStatus = async () => {
  if (!jobId.value) return;
  
  try {
    console.log('检查职位收藏状态，jobId:', jobId.value);
    const result = await isJobCollectedApi(jobId.value);
    isCollected.value = result === true;
    console.log('职位收藏状态检查结果:', isCollected.value);
  } catch (error) {
    console.log('检查职位收藏状态失败:', error);
  }
};

// 切换收藏状态
const toggleCollectJob = async () => {
  if (!jobId.value || collectLoading.value) return;
  
  collectLoading.value = true;
  
  try {
    if (isCollected.value) {
      // 取消收藏
      console.log('取消收藏职位，jobId:', jobId.value);
      await uncollectJobApi(jobId.value);
      isCollected.value = false;
      uni.showToast({
        title: '已取消收藏',
        icon: 'success',
        duration: 1500
      });
    } else {
      // 收藏职位
      console.log('收藏职位，jobId:', jobId.value);
      await collectJobApi(jobId.value);
      isCollected.value = true;
      uni.showToast({
        title: '收藏成功',
        icon: 'success',
        duration: 1500
      });
    }
  } catch (error) {
    console.log('收藏操作失败:', error);
    uni.showToast({
      title: isCollected.value ? '取消收藏失败' : '收藏失败',
      icon: 'none',
      duration: 2000
    });
  } finally {
    collectLoading.value = false;
  }
};

// 跳转到HR主页
const goToHrHome = () => {
  if (!jobDetail.value || !jobDetail.value.hrInfo || !jobDetail.value.hrInfo.hrUserId) {
    uni.showToast({
      title: 'HR信息获取失败',
      icon: 'none'
    });
    return;
  }
  
  uni.navigateTo({
    url: `/pages/candidate/position/hrView?hrId=${jobDetail.value.hrInfo.hrUserId}`
  });
};

// 移除了弹出层相关的取消和确认举报方法

// 格式化薪资
const formatSalary = (jobInfo) => {
  if (jobInfo.beginSalary && jobInfo.endSalary) {
    let salaryText = `${jobInfo.beginSalary}-${jobInfo.endSalary}K`;
    if (jobInfo.monthlySalary && jobInfo.monthlySalary > 0) {
      salaryText += `·${jobInfo.monthlySalary}薪`;
    }
    return salaryText;
  }
  return '面议';
};

// 格式化公司规模
const formatPeopleSize = (peopleSize) => {
  const value = dictionaryCacheManager.getValueByKeys('staff_size', peopleSize);
  return value || peopleSize;
};

// 格式化融资阶段
const formatFinancStage = (financStage) => {
  const value = dictionaryCacheManager.getValueByKeys('financing_status', financStage);
  return value || financStage;
};

// 处理职位标签
const processJobTags = (tags) => {
  if (!tags) return [];
  return tags.split(',').map(tag => tag.trim()).filter(tag => tag);
};

// 处理员工福利
const processBenefits = (companyInfo) => {
  const benefits = [];
  
  // 处理基础福利
  if (companyInfo.benefits) {
    const benefitsData = dictionaryCacheManager.formatMultipleValues('company_welfare', companyInfo.benefits);
    benefits.push(...benefitsData);
  }
  
  // 处理奖金福利 (注意：没有对应的字典数据，暂时跳过)
  // if (companyInfo.bonus) {
  //   const bonusData = dictionaryCacheManager.formatMultipleValues('bonus_type', companyInfo.bonus);
  //   benefits.push(...bonusData);
  // }
  
  // 处理补贴津贴
  if (companyInfo.subsidy) {
    const subsidyData = dictionaryCacheManager.formatMultipleValues('subsidy_allowance', companyInfo.subsidy);
    benefits.push(...subsidyData);
  }
  
  return benefits;
};

// 加载字典数据
const loadDictionaryData = async () => {
  try {
    // 检查缓存
    if (dictionaryCacheManager.hasData()) {
      console.log('使用缓存的字典数据');
      return;
    }

    // 从接口获取字典数据
    console.log('从接口获取字典数据...');
    const typeKeys = ['staff_size', 'financing_status', 'company_welfare', 'subsidy_allowance'];
    const dictionaryData = await getDictionaryDataListByTypesApi(typeKeys);
    
    console.log('获取到的字典数据:', dictionaryData);
    
    if (dictionaryData && typeof dictionaryData === 'object') {
      // 保存到缓存
      dictionaryCacheManager.setData(dictionaryData);
      console.log('字典数据已保存到缓存');
    }
  } catch (error) {
    console.error('获取字典数据失败:', error);
  }
};

// 获取职位详情
const fetchJobDetail = async () => {
  if (!jobId.value) {
    console.error('缺少jobId参数');
    loading.value = false;
    return;
  }

  try {
    loading.value = true;
    console.log('开始获取职位详情...', jobId.value);
    
    // 并行加载字典数据和职位详情
    const [dictionaryResult, jobDetailResult] = await Promise.allSettled([
      loadDictionaryData(),
      getJobSearchDetailApi(jobId.value)
    ]);

    if (jobDetailResult.status === 'fulfilled' && jobDetailResult.value) {
      jobDetail.value = jobDetailResult.value;
      console.log('获取职位详情成功:', jobDetail.value);
      
      // 处理职位标签
      jobTagsList.value = processJobTags(jobDetail.value.jobInfo.tags);
      
      // 处理员工福利
      allBenefits.value = processBenefits(jobDetail.value.companyInfo);
      
      console.log('处理后的标签:', jobTagsList.value);
      console.log('处理后的福利:', allBenefits.value);
      
      // 检查收藏状态
      await checkCollectStatus();
    } else {
      console.error('获取职位详情失败:', jobDetailResult.reason);
    }
  } catch (error) {
    console.error('获取职位详情失败:', error);
    uni.showToast({
      title: '获取职位详情失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 跳转到聊天页面
const goToChat = async () => {
  console.log(jobDetail.value);
  
  if (!jobDetail.value || !jobDetail.value.hrInfo) {
    uni.showToast({
      title: 'HR信息获取失败',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 创建会话
    console.log('创建聊天会话...');
    const sessionData = await createCandidateChatSessionApi(
      jobDetail.value.hrInfo.hrUserId,
      jobDetail.value.jobInfo.jobId
    );
    console.log('会话创建成功:', sessionData);
    
    // 将会话添加到本地存储
    const sessionStore = useSessionStore();
    sessionStore.upsertSession(sessionData);
    
    // 跳转到聊天页面
    uni.navigateTo({
      url: `/pages/candidate/chat?sessionId=${sessionData.id}&name=${encodeURIComponent(jobDetail.value.hrInfo.name || 'HR')}&hrId=${jobDetail.value.hrInfo.hrUserId}`
    });
  } catch (error) {
    console.error('创建会话失败:', error);
    uni.showToast({
      title: '进入聊天失败',
      icon: 'none'
    });
  }
};

// 投递简历并跳转到聊天页面
const goToChatAndApply = () => {
  if (!jobDetail.value || !jobDetail.value.hrInfo) {
    uni.showToast({
      title: 'HR信息获取失败',
      icon: 'none'
    });
    return;
  }
  
  // TODO: 这里可以添加投递简历的逻辑
  uni.showToast({
    title: '简历投递成功',
    icon: 'success',
    duration: 1500
  });
  
  // 延迟跳转到聊天页面
  setTimeout(() => {
    goToChat();
  }, 1500);
};

// 页面加载
onMounted(() => {
  // 参数获取和数据加载已经在onLoad中处理
});
</script>

<style scoped lang="less">
.position-detail-container {
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 120rpx; /* 为底部按钮留空间 */
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.header-btn {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-btn-icon {
  width: 36rpx;
  height: 36rpx;
}

.header-btn.collecting {
  opacity: 0.6;
  pointer-events: none;
}

/* 加载和错误状态 */
.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-text,
.error-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.retry-btn {
  background-color: #00bdb4;
  padding: 20rpx 40rpx;
  border-radius: 8rpx;
}

.retry-text {
  color: #fff;
  font-size: 28rpx;
}

/* 内容区域 */
.content {
  padding: 0;
}

/* 职位基本信息 */
.job-basic-info {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.job-name {
  font-size: 44rpx;
  font-weight: 600;
  color: #1a1a1a;
  flex: 1;
  margin-right: 20rpx;
  font-family: "PingFang SC", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Microsoft YaHei", sans-serif;
}

.job-salary {
  font-size: 36rpx;
  font-weight: 600;
  color: #00bdb4;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.job-requirements {
  display: flex;
  gap: 40rpx;
  margin-bottom: 30rpx;
}

.requirement-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.requirement-icon {
  width: 32rpx;
  height: 32rpx;
}

.requirement-text {
  font-size: 28rpx;
  color: #666;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* HR信息区域 */
.hr-section {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.hr-content {
  display: flex;
  align-items: center;
  gap: 20rpx;
  flex: 1;
}

.hr-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.hr-info {
  flex: 1;
}

.hr-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.hr-details {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.hr-details .company-name,
.hr-position {
  font-size: 28rpx;
  color: #666;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.separator {
  font-size: 26rpx;
  color: #999;
}

/* 通用section样式 */
.job-detail-section,
.benefits-section,
.company-section {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 30rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 职位标签 */
.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.job-tag {
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 12rpx 20rpx;
}

.tag-text {
  font-size: 26rpx;
  color: #666;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 职位描述 */
.job-description {
  margin-top: 20rpx;
}

.description-html {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 去掉富文本中列表的默认间距 */
:deep(.description-html ol),
:deep(.description-html ul) {
  padding-left: 0 !important;
  margin-left: 0 !important;
}

:deep(.description-html li) {
  list-style-position: inside;
}

/* 员工福利 */
.benefits-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.benefit-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  padding: 16rpx 20rpx;
}

.benefit-icon {
  width: 32rpx;
  height: 32rpx;
}

.benefit-text {
  font-size: 26rpx;
  color: #666;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 公司信息 */
.company-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.company-logo {
  width: 100rpx;
  height: 100rpx;
  border-radius: 12rpx;
  flex-shrink: 0;
}

.company-details {
  flex: 1;
}

.company-details .company-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.company-info-list {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex-wrap: wrap;
}

.info-item {
  font-size: 26rpx;
  color: #666;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 底部按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.communicate-btn {
  background-color: #f8f8f8;
  border: 1px solid #e0e0e0;
}

.apply-btn {
  background-color: #00bdb4;
}

.btn-text {
  font-size: 32rpx;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.communicate-btn .btn-text {
  color: #333;
}

.apply-btn .btn-text {
  color: #fff;
}
</style>

